package com.serverGroup.shiro;

import java.io.Serializable;
import java.sql.Date;
import java.util.concurrent.TimeUnit;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import com.serverGroup.util.SerializeUtil;

/**
 * Title: SessionDao Description: 这里是配置SessionDao用于实现session共享
 * 
 * @author Hr222
 * @date 2018年8月23日
 */
public class SessionDao extends EnterpriseCacheSessionDAO {

	@Autowired
	private RedisTemplate<String, Session> redisTemplate;

	@Override
	protected Serializable doCreate(Session session) {
		// TODO Auto-generated method stub
		Serializable sessionId = generateSessionId(session);
		assignSessionId(session, sessionId);
		ValueOperations<String, Session> valueOperations = redisTemplate.opsForValue();
		valueOperations.set("session:" + sessionId.toString(), session);
		return sessionId;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		// TODO Auto-generated method stub
		BoundValueOperations<String, Session> bvo = redisTemplate.boundValueOps("session:" + sessionId.toString());
		Session session = bvo.get();
		return session;
	}

	@Override
	protected void doUpdate(Session session) {
		// TODO Auto-generated method stub
		
		if (session instanceof  ValidatingSession && !((ValidatingSession) session).isValid()) {
			return;
		}
		BoundValueOperations<String, Session> bvo = redisTemplate.boundValueOps("session:" + session.getId().toString());
		Session thisSession = bvo.get();
		if (thisSession != null) {
			bvo.set(session, 30, TimeUnit.MINUTES);
		}
	}

	@Override
	protected void doDelete(Session session) {
		// TODO Auto-generated method stub
		BoundValueOperations<String, Session> bvo = redisTemplate.boundValueOps("session:" + session.getId().toString());
		bvo.expireAt(new Date(0));
		super.doDelete(session);
	}

	public RedisTemplate<String, Session> getRedisTemplate() {
		return redisTemplate;
	}

	public void setRedisTemplate(RedisTemplate<String, Session> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

}
